package SmartFleet.Car;

import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import linker.ClientLinker;
import linker.exception.CanNotCreateSocketException;
import linker.exception.CanNotWriteObjectException;
import smartfleet.communication.carrwprotocol.CarInfo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class CarInStationService extends Service {
	
	private static SmartFleetCar	MAIN_ACTIVITY;
	
	private String					ip		= "194.210.228.217";
	private Timer					timer	= new Timer();
	
	private void startservice() {

		this.timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {

				Iterator iterator = MAIN_ACTIVITY.getMyCar().getStation().keySet().iterator();
				while (iterator.hasNext()) {
					int key = (Integer) iterator.next();
					if (MAIN_ACTIVITY.getMyCar().getMyLocation().getLatitudeE6() == MAIN_ACTIVITY.getMyCar().getStation().get(key).getGeoLat() && MAIN_ACTIVITY.getMyCar().getMyLocation().getLongitudeE6() == MAIN_ACTIVITY.getMyCar().getStation().get(key).getGeoLong() && MAIN_ACTIVITY.getMyCar().getHeight() == 0) {
						
						try {
							ClientLinker link = new ClientLinker(MAIN_ACTIVITY.getMyCar().getStation().get(key).getIp(), MAIN_ACTIVITY.getMyCar().getStation().get(key).getPort());
							CarInfo car = new CarInfo(MAIN_ACTIVITY.getMyCar().getId(), 0, 0, CarInStationService.this.ip, MAIN_ACTIVITY.getMyCar().getPort());
							link.writeObject(car);
							
						} catch (CanNotCreateSocketException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (CanNotWriteObjectException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
				}
				
			}
			
		}, 0, 3000);
		
		;
	}
	
	private void stopservice() {

		if (this.timer != null)
			this.timer.cancel();
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}
	
	@Override
	public void onCreate() {

		super.onCreate();
		startservice();
	}
	
	@Override
	public void onDestroy() {

		super.onDestroy();
		stopservice();
	}
	
	public static void setMainActivity(SmartFleetCar activity) {

		MAIN_ACTIVITY = activity;
	}
}
